<?php
error_reporting(0);
include 'db-connection/conn.php';
include_once 'classes/clsEssential.php';

//define a maxim size for the uploaded images in Kb

define ("MAX_SIZE","5000"); 
error_reporting(1);
session_start();

$allowed_filetypes = array('.jpg','.gif','.bmp','.png','.jpeg','.JPG','.GIF','.BMP','.PNG','.JPEG'); // These will be the types of file that will pass the validation.

$uploaddir = dirname($_SERVER['SCRIPT_FILENAME'])."/showcase-image/";

/*-------------------------------------------------------------------------
* First part of this script is for regular upload method (RFC based) 
*/
if(!isset($_REQUEST['chunkedUpload']))
{
	if(isset($_POST['MultiPowUpload_browserCookie']))
	{
		$cookies = split(";", $_POST['MultiPowUpload_browserCookie']);
		foreach($cookies as $value)
		{
			$namevalcookies = split("=", $value);	
			$browsercookie[trim($namevalcookies[0])] =  trim($namevalcookies[1]);
		}
		$_COOKIE = $browsercookie;
	}
	//restore session if possible
	if(isset($browsercookie) && isset($browsercookie['PHPSESSID']))
	{	
		session_id($browsercookie['PHPSESSID']);
		session_start();
	}

	
	if(count($_FILES) > 0)
	{
		$arrfile = pos($_FILES);
		
		$ext = substr($arrfile['name'], strpos($arrfile['name'],'.'), strlen($arrfile['name'])-1); // Get the extension from the filename.
 
	   // Check if the filetype is allowed, if not DIE and inform the user.
	   if(!in_array($ext,$allowed_filetypes))
		  die('The file you attempted to upload is not allowed.');
		  
		   $size=filesize($arrfile['tmp_name']);

			//compare the size with the maxim size we defined and print error if bigger
			if ($size > MAX_SIZE*1024)
			 die('The file '.basename($arrfile['name']).' is too large to upload.');
		
		 $uploaddir1 = $uploaddir;
		 $uploadfile = $uploaddir1 . basename($arrfile['name']);
		
		if (move_uploaded_file($arrfile['tmp_name'], $uploadfile))
		{
		   echo "File " . basename($arrfile['name']) . " was successfully uploaded.<br />";
		   echo "File Path :showcase-image/".basename($arrfile['name']);
		}

		$TotalImagePath ="showcase-image/".basename($arrfile['name']);
		   
		createThumbs($uploaddir1,$uploaddir1,basename($arrfile['name']),400);
		
		mkdir($uploaddir."/thumbs/");
		createThumbs($uploaddir1,$uploaddir."/thumbs/",basename($arrfile['name']),60);
		$orgImgPath = "/org/".basename($arrfile['name']);
		SavingImagePathToDB($TotalImagePath);
		   
	}
	echo '<br>'; // At least one symbol should be sent to response!!!
}
/*-------------------------------------------------------------------------
* The second part is for chunked upload method used by silverlight uploader
*/
else
{
	error_reporting(E_ERROR);
	set_error_handler ('err_handler');

	$filename = isset($_GET["FileName"]) ? str_replace("../", "", $_GET["FileName"]) : "";
	$complete = isset($_GET["Complete"]) ? strtolower($_GET["Complete"]) == "true" ? true : false : true;
	$querySize = isset($_GET["QuerySize"]) ? strtolower($_GET["QuerySize"]) == "true" ? true : false : false;
	$startByte = isset($_GET["StartByte"]) ? (int)$_GET["StartByte"] : 0;
	$comment = isset($_GET["Comment"]) ? $_GET["Comment"] : "";
	$tag = isset($_GET["Tag"]) ? $_GET["Tag"] : "";
	$isMultiPart = isset($_GET["isMultiPart"]) ? $_GET["isMultiPart"] == "true" : false;
	$dirPath = $uploaddir;

	$filePath = $dirPath . "/" . $filename;

	// If you use file names in national encodings, change the $filePath assignment consider
	// encoding conversion by functions 'iconv()' or 'mb_convert_encoding()' as shown below:
	// $codepage = "windows-1251";
	// $filePath = $dirPath . "/" . mb_convert_encoding($filename, $codepage , 'UTF-8');
	// $filePath = $dirPath . "/" . iconv("utf-8", $codepage, $filename);

	if ($querySize)
	{
		if (file_exists($dirPath) && is_dir($dirPath))
		{
			if (file_exists($filePath))
			{
				print filesize($filePath);
			}
			else
				print "0";
		}
		else print "The path for file storage not found on the server.";
	}
	else
	{
		//if mulltipart mode and there is no file form field in request , then write error
		if($isMultiPart && count($_FILES) <= 0)
		{
			echo "Error: No chunk for save.";	
			exit;
		}
		if ($startByte > 0 && file_exists($filePath))
		{
			$isCreate = false;
			$file = fopen($filePath, "a");
		}
		else
		{
			$isCreate = true;
			$file = fopen($filePath, "w");
		}
			
		if (!is_writable($filePath))
		{
			print "Error: cannot write to the specified directory.";
			exit;
		}
			
		//logic to read and save chunk posted with multipart
		//Multipart allow us to send form data in request body
		if($isMultiPart)
		{
			$filearr = pos($_FILES);		
			if(!$input = file_get_contents($filearr['tmp_name']))
			{
				echo "Error: Can't read from file.";
				exit;
			}
		}
		//raw data
		else
			$input = file_get_contents("php://input");
		if(!fwrite($file, $input)) 
			echo "Error: Can't write to file.";
		fclose($file);
			
		if ($complete)
		{
			
			echo "File " . basename($filePath) . " was successfully uploaded.<br/>";
			echo "File Path:".$filePath;
			// Place here the code making postprocessing of the uploaded file (moving to other location, database, etc).
		}
		else
		{
			if ($isCreate) print "Creating file..." ;
			else print "Write chunk since byte " . $startByte;
		}
	}

	function err_handler ($errno, $errstr, $errfile, $errline)
	{
		print "Write error: " . $errstr;
	}
}

function createThumbs( $pathToImages, $pathToThumbs, $filename, $thumbHeight ) 
{
  // open the directory
  $dir = opendir( $pathToImages );


    // parse path for the extension
    $info = pathinfo($pathToImages . $filename);
    // continue only if this is a JPEG image
	/*if(thumbHeight != '400')
      echo "<br />Creating thumbnail for {$filename} <br />";*/

      // load image and get image size
      $img = imagecreatefromjpeg( "{$pathToImages}{$filename}" );
      $width = imagesx( $img );
      $height = imagesy( $img );

      // calculate thumbnail size
	  $new_height = "160";
      //$new_width = floor( $height * ( $thumbHeight / $width ) );
      //$new_width = floor( $thumbHeight * 1.5 );
	  $new_width = "720";

      // create a new temporary image
      $tmp_img = imagecreatetruecolor( $new_width, $new_height );

      // copy and resize old image into new image 
      imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

      // save thumbnail into a file
      imagejpeg( $tmp_img, "{$pathToThumbs}{$filename}" );

}


function SavingImagePathToDB($imagePath)
{
	if(strlen($imagePath)>0)
	{
		$sqlInsertNew = "INSERT INTO tbl_showcase_slideshow (image_path,is_active) VALUES ('".$imagePath."','Y')";
		mysql_query($sqlInsertNew);
		
	}
}

?> 